package com.openingedu.mba.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.openingedu.mba.common.CommConsts;
import com.openingedu.mba.entity.OrderVO;
import com.openingedu.mba.persist.DataHelper;
import com.openingedu.mba.persist.DbOrder;
import com.openingedu.mba.util.DESEncrypt;
import com.openingedu.mba.util.DeviceUtil;
import com.openingedu.mba.util.GsonUtil;
import com.openingedu.mba.util.MD5;

public class OrderService {

	private static final String TAG = OrderService.class.getSimpleName();

	/**
	 * 列出所有未支付及待验证订单
	 * @param mContext
	 * @return
	 */
	public List<DbOrder> listOrder(Context mContext) {
		DataHelper dataHelper = new DataHelper(mContext);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			queryBuilder.orderBy("orderStatus", true);
			queryBuilder.orderBy("orderTime", false);
			orderList = queryBuilder.query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderList;
	}
	
	/**
	 * 保存订单
	 * @param mContext
	 * @param order
	 */
	public void persistOrder(Context mContext, DbOrder order) {
		DataHelper dataHelper = new DataHelper(mContext);
		try {
			DbOrder dbOrder = findOrder(mContext, order.getOrderID());
			if (dbOrder != null) {
				dataHelper.getOrderDao().update(order);
			}
			else {
				dataHelper.getOrderDao().create(order);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据orderID查询订单
	 * @param context
	 * @param orderID
	 * @return
	 */
	public DbOrder findOrder(Context context, String orderID) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			Where<DbOrder, Long> where = queryBuilder.where();
			where.eq("orderID", orderID);
			orderList = queryBuilder.query();
			if (orderList!=null && orderList.size() > 0) {
				return orderList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询未支付试卷订单
	 * @param context
	 * @param paperID
	 * @return
	 */
	public DbOrder findNonePaidOrder(Context context, Integer paperID) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			Where<DbOrder, Long> where = queryBuilder.where();
			where.eq("paperID", paperID);
			where.and();
			where.eq("orderStatus", CommConsts.Order.NONE_PAID);
			orderList = queryBuilder.query();
			if (orderList!=null && orderList.size() > 0) {
				return orderList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询未支付订单
	 * @param context
	 * @return
	 */
	public List<DbOrder> findNonePaidOrder(Context context) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			Where<DbOrder, Long> where = queryBuilder.where();
			where.eq("orderStatus", CommConsts.Order.NONE_PAID);
			return queryBuilder.query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询待验证订单
	 * @param context
	 * @return
	 */
	public List<DbOrder> findWaitingPaidOrder(Context context) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			Where<DbOrder, Long> where = queryBuilder.where();
			where.eq("orderStatus", CommConsts.Order.WAITING_PAID);
			return queryBuilder.query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void markOrderWaitingPaid(Context context, DbOrder order) {
		DataHelper dataHelper = new DataHelper(context);
		order.setOrderStatus(CommConsts.Order.WAITING_PAID);
		try {
			dataHelper.getOrderDao().update(order);
		} catch (SQLException e) {
			e.printStackTrace();
			Log.e(TAG, "update Order status waiting error." + e.getMessage(), e);
		}
	}
	
	private void markOrderPaid(Context context, DbOrder order) {
		DataHelper dataHelper = new DataHelper(context);
		order.setOrderStatus(CommConsts.Order.PAID);
		try {
			dataHelper.getOrderDao().update(order);
		} catch (SQLException e) {
			e.printStackTrace();
			Log.e(TAG, "update Order status paid error." + e.getMessage(), e);
		}
	}

	public boolean checkOrderStatus(Context mContext, String orderStr) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(CommConsts.siteURL);
		// TODO getProfile from Profile
		String androidID = DeviceUtil.getAndroidID(mContext);
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + androidID);
		
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "303");
		// TODO deviceID
		reqMap.put("deviceID", 1);
		reqMap.put("orderStr", orderStr);
		reqMap.put("secureKey", md5Key);
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("req", GsonUtil.otj(reqMap)));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httpPost);
			int reponseCode = response.getStatusLine().getStatusCode();        //获得服务器的响应码
			if (reponseCode == HttpStatus.SC_OK) {
				String resultStr = EntityUtils.toString(response.getEntity());
				Log.i(TAG, "resultStr=" + resultStr);
				Map<String, Object> map = GsonUtil.stm(resultStr);
				Integer result = GsonUtil.oti(map.get("Result"));
				boolean orderFinish = false;
				// 操作成功
				if (result == 0) {
					String orders = GsonUtil.otj(map.get("orderList"));
					List<OrderVO> orderList = GsonUtil.stl(orders,new TypeToken<List<OrderVO>>() {}.getType());
					for (OrderVO orderVO : orderList) {
						// 订单已经完成
						String status = String.valueOf(orderVO.getOrderStatus());
						if (status.equals("1")) {
							DbOrder dbOrder = findOrderByDID(mContext, Integer.valueOf(orderVO.getOrderDID()));
							if (dbOrder!=null) {
								Log.i(TAG, "update server order paid. order=" + orderVO);
								markOrderPaid(mContext, dbOrder);
								// 生成消息
								CommService commService = new CommService();
								commService.createMessage(mContext, "您购买的订单[" + dbOrder.getOrderID() + "]已经支付完成，请在试题商店中下载。");
							}
							else {
								Log.e(TAG, "update server order finish error, can not find order in database. order=" + orderVO);
							}
							orderFinish = true;
						}
						else {
							Log.i(TAG, "order is still waiting paid. order=" + orderVO);
							orderFinish = false;
						}
					}
				}
				else {
					Log.e(TAG, "check order status result failure. result=" + result);
				}
				return orderFinish;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}

	private DbOrder findOrderByDID(Context context, Integer orderDID) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbOrder> orderList = null;
		try {
			QueryBuilder<DbOrder, Long> queryBuilder = dataHelper.getOrderDao().queryBuilder();
			Where<DbOrder, Long> where = queryBuilder.where();
			where.eq("orderDID", orderDID);
			orderList = queryBuilder.query();
			if (orderList!=null && orderList.size() > 0) {
				return orderList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
